package com.semidata.trp.monitor.log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.semidata.rtd.core.log.LogBlockHandler;
import com.semidata.rtd.core.log.LogEvent;
import com.semidata.rtd.core.log.LogEventHandler;
import com.semidata.trp.monitor.config.Config;

public class MonitorLogHandler extends LogEventHandler {

	public static final String NAME = "MONITOR";

	private static Config config = Config.getConfig();

	public MonitorLogHandler(LogBlockHandler handler) {
		super(handler);
	}

	@Override
	protected File getLogFile(LogEvent event, String root) {

		if (event.getType() == NAME) {
			Date date = new Date(event.getTimestamp());
			String dirName = new SimpleDateFormat("yyyyMMdd").format(date);
			String fileName = new SimpleDateFormat("yyyyMMddHHmm").format(date);
			fileName = fileName.concat(".");
			fileName = fileName.concat(config.getMonitorId());
			fileName = fileName.concat(".log");
			File dir = new File(new File(root, event.getType().toLowerCase()),
					dirName);
			if (dir.exists()) {
				if (!dir.isDirectory() || !dir.canExecute() || !dir.canWrite())
					return null;
			} else {
				if (!dir.mkdirs())
					return null;
			}
			File file = new File(dir, fileName);
			if (file.exists()) {
				if (!file.isFile() || !file.canWrite())
					return null;
			}
			return file;
		} else {
			return null;
		}
	}

	@Override
	protected String getLogContent(LogEvent event) {
		if (event.getType() != NAME)
			return null;

		StringBuffer sb = new StringBuffer();
		sb.append(event.getContent());
		if (!event.getContent().endsWith("\n"))
			sb.append('\n');
		return sb.toString();
	}

	@Override
	protected boolean verify(String root) {
		File dir = new File(root, NAME.toLowerCase());
		if (dir.exists()) {
			if (!dir.isDirectory() || !dir.canExecute() || !dir.canWrite())
				return false;
		} else {
			if (!dir.mkdirs())
				return false;
		}
		return true;
	}
}
